package jgo.plugins;

import jgo.Context;
import jgo.Handler;
import jgo.JGo;
import jgo.Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class StaticFilePlugin extends Plugin {
    private static final Logger logger = LoggerFactory.getLogger(StaticFilePlugin.class);
    private String urlPath;
    private String directory;

    public StaticFilePlugin(String urlPath, String directory) {
        this.urlPath = urlPath;
        this.directory = directory;
    }

    @Override
    public void init(JGo jgo) {
        logger.info("初始化 StaticFilePlugin: urlPath={}, directory={}", urlPath, directory);
        jgo.get(urlPath + "/*", createFileHandler());
    }

    private Handler createFileHandler() {
        return ctx -> {
            String requestPath = ctx.getPath().substring(urlPath.length());
            Path filePath = Paths.get(directory, requestPath);
            File file = filePath.toFile();

            if (!file.exists() || file.isDirectory()) {
                ctx.status(404).string("File not found");
                return;
            }

            try {
                String mimeType = Files.probeContentType(filePath);
                byte[] fileContent = Files.readAllBytes(filePath);

                ctx.contentType(mimeType != null ? mimeType : "application/octet-stream");
                ctx.status(200);
                ctx.body(fileContent);
            } catch (IOException e) {
                logger.error("Error serving file: {}", filePath, e);
                ctx.status(500).string("Internal Server Error");
            }
        };
    }
}